# ---- revision log handling ----------------------------

import os, string, traceback
import vcs
from logParser import Revision

from TCSettings import BuildCmdOptions, readSettings, TEST
 
TRUE = 1
FALSE = 0
NL	    = '\n'
gMod="TClog:"
VERBOSE = TRUE

#TEST=0         # no debugging
TEST=1         # trace function calls
#TEST=2         # for  debugging 
#TEST=3         # for HEAVY debugging 

class TClog:
	workFiles = []
	workFile = ''
	count = 0
	valid = TRUE
	CMD		= 'teamc part -view %s/%s -long '
	logText = ''

	def __init__(self, workFile, debug=TEST):
		marker="(TClog) __init__: "
		if debug > 0: 
			print "start", gMod+marker+NL,
		self.workFiles = string.split(workFile, ' ')
		if debug > 1: print marker, self.workFiles
		self.workFile = workFile
		self.count = 0
		self.valid = TRUE
		
		self.next(debug)
		if debug > 0: 
			print "end", gMod+marker+NL,
		
	def readConfigFile(self, filename):
		filename = os.path.normpath(os.path.expandvars(filename))
		fileContent = ''
		if vcs.is_readable(filename):
			fileObject = open(filename)
			fileContent = fileObject.read()
			fileContent = string.strip(fileContent)
			fileObject.close()
		return fileContent	

	def next(self, debug=TEST):
		marker="next: "
		if debug > 0: 
			print "start", gMod+marker+NL,
		try:
			newWorkFile = self.workFiles[self.count]
		except:
			if debug > 1: print marker, "End of files reached!"
			# set to "invalid" but leave the workFile as it is
			self.valid = FALSE
			if debug > 0: 
				print "end", gMod+marker+NL,
			return
		self.workFile = newWorkFile
		options = BuildCmdOptions(FALSE,FALSE,VERBOSE)
		cmd = self.CMD % (vcs.projectDir, self.workFile)
		cmd = cmd + options + ";"
		if debug > 1: print marker, "cmd = ", cmd
		self.logText = vcs.getoutput(cmd)
		if debug > 2: 
			print marker, "logText: "
			print logText
		self.count = self.count + 1
		if debug > 0: 
			print "end", gMod+marker+NL,
		
	def __nonzero__(self):
		return self.valid

	def getText(self):
		return self.logText

	def work_file(self):
		return self.workFile

	def convert_rev(self, rev_string, debug=TEST):
		marker=gMod+"convert_rev: "
		"""Convert workarea:rev to (workarea)rev since SNiFF don't like :"""
		try:
			[workArea, HeadRev] = string.split(rev_string, ":")
		except:
			if debug > 1: print marker, "Parsing Error - colon missing? ", rev_string
			# this raise generate an Python error
			#raise "convert_rev exception"
			return ''
		return "%s.%s" % (workArea, HeadRev)
		#return "%s.%s" % (HeadRev, workArea)
		#return "1.%s" % (HeadRev)

	def lockers(self, debug=TEST):
		marker="lockers"
		if debug > 0: 
			print "start", gMod+marker+NL
		theStart = string.find(self.logText, NL+"locks:"+NL)
		if theStart <= 0:
			return ''
		theLockers = ""
		lockerList = string.split(self.logText[theStart+1:], NL)
		#if debug > 1: print marker, lockerList
		for curLine in lockerList[3:]:
			if not curLine:
				break
			curList = string.split(string.strip(curLine))
			if debug > 1: print marker, curList
			print marker, curLine
			print marker, curList
			#check if tere is a loker name
			if string.strip(curLine[0:10]) == "":
				lockerName = ""
			else:
				lockerName = curList[0]
			# normally the revision string is a third element after splitting
			# but wnhen one of previous was empty then it could be first or second element
			# so we have to check it
			
			# due the raise error in convert_rev exception handling commented	
			#try:
			#	newLockers = "%s: %s " % (lockerName, self.convert_rev(curList[2]))
			#except "convert_rev exception":
			#	try:
			#		if debug > 1: print marker, "convert_rev(curList[1])", curList[1]
			#		newLockers = "%s: %s " % (lockerName, self.convert_rev(curList[1]))
			#	except "convert_rev exception":
			#		try:
			#			if debug > 1: print marker, "convert_rev(curList[1])", curList[1]
			#			newLockers = "%s: %s " % (lockerName, self.convert_rev(curList[0]))
			#		except "convert_rev exception":
			#			if debug > 1:
			#				print marker, "Exception caught, Parsing Error? ", lockerList
			#				traceback.print_exc()
			#			pass
			
			if debug > 1: print marker, "convert_rev(curList[2])", curList[2]
			#print marker, "convert_rev(curList[2])", curList[2]
			rev_str = self.convert_rev(curList[2])
			if len(rev_str)==0:
				if debug > 1: print marker, "convert_rev(curList[1])", curList[1]
				#print marker, "convert_rev(curList[1])", curList[1]
				rev_str = self.convert_rev(curList[1])
				if len(rev_str)==0:
					if debug > 1: print marker, "convert_rev(curList[0])", curList[0]
					#print marker, "convert_rev(curList[0])", curList[0]
					rev_str = self.convert_rev(curList[0])
			newLockers = "%s: %s " % (lockerName, rev_str)
			if debug > 1: print marker, " newLockers:", newLockers
			theLockers = theLockers + newLockers
		if debug > 0: 
			print "end", gMod+marker+NL
		return theLockers

	def head_rev(self, debug=TEST):
		marker="head_rev"
		if debug > 0: 
			print "start", gMod+marker+NL
		theStart = string.find(self.logText, NL+"currentVersion")
		if theStart > 0:
			theEnd = string.find(self.logText, NL, theStart+1)
			if theEnd <= 0: return ''
			theLine = self.logText[theStart+1:theEnd]
			if debug > 0: 
				print "end", gMod+marker+NL
			return self.convert_rev(string.split(theLine)[1])
		else:
			if debug > 0: 
				print "end", gMod+marker+NL
			return ''
	
	def symbolstr(self):
		marker=gMod+"symbolstr: "
		return ""
	
	def history_str(self):
		thePos = string.find(self.logText, NL+"versions:")
		if thePos > 0:
			versionText = self.logText[thePos + 11:]
			return versionText
		return ''
	
	def revision_list(self, debug=TEST):
		"""Returns a list of Revisions"""
		marker="revision_list"
		if debug > 0: 
			print "start", gMod+marker+NL
		result=[]
		try:
			for curLine in string.split(self.history_str(), NL)[2:]:
				if debug > 2: print marker,':', curLine
				curList = string.split(curLine)
				if len(curList) !=5 : 
					continue
				[ user, date, time, changeType, version ] = curList
				curRev = Revision(self.convert_rev(version))
#				curRev.rev = version
				curRev.author = user
				curRev.date = date + " " + time
				curRev.lines = changeType
				result.append(curRev)
		except:
			if debug > 1:
				print marker
				traceback.print_exc()
			pass
		if debug > 1: print marker, result
		if debug > 0: 
			print "start", gMod+marker+NL
		return result

